import { Processor, IProcessor } from '@midwayjs/bull';
import { FORMAT, Inject } from '@midwayjs/decorator';
import { RedisService } from '@midwayjs/redis';

import { InjectEntityModel } from '@midwayjs/typeorm';
import { UserEntity } from 'src/entity/userinfo/user';
import { UserHistoryEntity } from 'src/entity/userinfo/userhistory';
import { Repository } from 'typeorm';



@Processor('Updatahistory', {
  repeat: {
    // cron: FORMAT.CRONTAB.EVERY_PER_30_SECOND
   cron: FORMAT.CRONTAB.EVERY_DAY  // 每天零点 开始导入 用户浏览记录进入数据库
  }
})
export class Updatahistory implements IProcessor {
  @Inject()
  logger;
  @InjectEntityModel(UserEntity)
  UserModel: Repository<UserEntity>; 
  @InjectEntityModel(UserHistoryEntity)
  UserHistoryModel: Repository<UserHistoryEntity>; 



  @Inject()
  redisService: RedisService;

  async execute() {
        console.log("定时任务");  
        //获取所有用户
       let result    =  await this.UserModel.find({ select: ['id'] })
       console.log("定时任务", result);
        
       //     对所有用户进行遍历,查询redis 的浏览记录
    result.forEach( async v =>{
            let get1 :any  ;
               get1      =await   this.redisService.get('userhistory:'+v.id+"");
              if(get1 == null){
                 console.log('get1null',get1);
                 get1 = '{}' 
              }
              get1  =  JSON.parse(get1)
              console.log("解析得到的对象",get1);
              
              for( let key  in  get1 ){
                 
                    //  将浏览记录存入数据库
                    let r1   =await this.UserHistoryModel.findOne( { where :{  novel:  Number(key)  , user:v.id    } } )
                    console.log( "查询数据库结果",r1);
                        if(r1){
                            r1.part = get1[key]
                            this.UserHistoryModel.save(r1)
                        }else{
                            this.UserHistoryModel.save({  novel:  Number(key)  , user:v.id  , part:get1[key] })
                        }
              }


    })

  }
}